<template>
  <div class="wrap">
    <div class="panel">
      <h2>登录</h2>
      <form class="form" @submit.prevent="submit">
        <div class="field">
          <label>邮箱</label>
          <input v-model.trim="email" type="email" required autocomplete="username" />
        </div>
        <div class="field">
          <label>密码</label>
          <input v-model="password" type="password" required autocomplete="current-password" />
        </div>
        <button :disabled="loading">登录</button>
        <a class="link" @click.prevent="$router.push('/register')">没有账号？去注册</a>
        <p v-if="error" class="err">{{ error }}</p>
      </form>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
export default { name: 'LoginPage',
  setup(){
    const email = ref(''); const password = ref('')
    const loading = ref(false); const error = ref('')
    const router = useRouter(); const route = useRoute()
    const auth = useAuthStore()
    const submit = async () => {
      error.value=''; loading.value=true
      try{ await auth.login(email.value, password.value); router.replace(route.query.redirect || '/home') }
      catch(e){ error.value = e?.response?.data?.message || '登录失败' }
      finally{ loading.value=false }
    }
    return { email, password, loading, error, submit }
  }
}
</script>

<style src="./auth.css" scoped></style>
